package com.reggielcy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggielcy.common.BaseContext;
import com.reggielcy.common.R;
import com.reggielcy.entity.ShoppingCart;
import com.reggielcy.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @auther teacher
 * @date 2024/3/30
 * @project reggie_take_out
 */

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;


    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){

        log.info("shoppingCart={}", shoppingCart);

        //1.获取当前用户的Id，指定当前购物车数据是哪个用户的
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        //构造条件构造器
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        Long dishId = shoppingCart.getDishId();

        if (dishId!=null){
            //新增菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);

        }else {
            //新增套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());

        }

        //2.根据user_id查询shopping——cart表是否存在菜品 或套餐
        ShoppingCart shoppingCart1 = shoppingCartService.getOne(queryWrapper);

        if (shoppingCart1!=null){
            //3.如果已存在，则购物车的number+1
            shoppingCart1.setNumber(shoppingCart1.getNumber()+1);

            shoppingCartService.updateById(shoppingCart1);

        }else {
            //4.否则，插入这条数据，并设置number为1
            shoppingCart.setNumber(1);
            shoppingCart1=shoppingCart;
            shoppingCartService.save(shoppingCart1);
        }
        return R.success(shoppingCart1);
    }
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){

        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());

        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);

        return R.success(shoppingCartList);
    }

    @DeleteMapping("/clean")
    public R<String> delete(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());

        boolean remove = shoppingCartService.remove(queryWrapper);

        return R.success("清除购物车成功");
    }






}
